package com.vids.task;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RequiredArgsConstructor
public class CopyFilesTask implements Runnable {

    private final  String ape_root;

    private final  String viid_root;


    private  void copyFile(File source, File dest) {
        try {
            FileUtils.copyFile(source, dest);
        }catch (IOException ioe)
        {
            log.info("Copy file io failed",ioe);
        } catch (Exception e)
        {
            log.info("Copy file failed",e);
        }
    }

    @Override
    public void run() {
        String[] image_types = {"person", "motor", "non_motor"};
        String[] ape_ids = {"42022201001320058103", "42022206001320058078"};

        LocalDateTime before_1hour_now = LocalDateTime.now().minusHours(1);
        int hour = before_1hour_now.getHour();
        String datePath = before_1hour_now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String src_dir;
        String dest_dir;

        for (String image_type : image_types) {
            for (String ape_id : ape_ids) {
                src_dir = ape_root + datePath + "/" + hour + "/"+ image_type +"/"+ ape_id+"/";

                log.info("src_dir is "+src_dir);
                dest_dir =  viid_root + datePath + "/" + hour + "/"+ image_type +"/"+ ape_id+"/";
                log.info("dest_dir is "+dest_dir);

                File f_dest_dir = new  File(dest_dir);
                if (!f_dest_dir.exists())
                    f_dest_dir.mkdirs();

                File f_src_dir = new  File(src_dir);
                if (f_src_dir.exists())
                {
                    File[] src_files = f_src_dir.listFiles();
                    if (src_files == null)
                    {
                        log.info("src file does not exist. ");
                    }else {
                        log.info("src_files count= " + src_files.length);
                        for (File f : src_files) {
//                            log.info("src file name: " + f.getName());
//                            log.info("dest file name:" + dest_dir + f.getName());
                            copyFile(f, new File(dest_dir + f.getName()));
                        }
                    }
                }

            }
        }
    }
}
